package com.Smart.smartscals.DataBase;



import com.Smart.smartscals.Entity.EntityConversionTime;
import com.Smart.smartscals.Entity.ReciveBodyInfoEntity;
import com.Smart.smartscals.Entity.SaveBodyInfoEntity;
import com.Smart.smartscals.Utils.MSConversionToValues;

import android.content.Context;


/**
 * 此类用于更新数据库数据的类
 * @author Administrator
 *
 */
public class UpLoadDataBaseUtils {
	private DataBaseService mDataService;
	private Context context;
	private boolean boo;
	//		if (cursor.moveToLast()) {
	//		    // 该cursor是最后一条数据
	//		}
	/**
	 * 插入bodyInformation的函数
	 * @param bodyInfoEntity
	 * 
	 */
	public UpLoadDataBaseUtils(Context context){
		this.context = context;

	}
	public void insertBodyInfo(SaveBodyInfoEntity bodyInfoEntity){
		mDataService = DataBaseService.getInstance(context);
		long mdate = bodyInfoEntity.getDate();
		String muserName = bodyInfoEntity.getUserName();
		
		SeletLastDataBaseUtilt getLastDatebBase = new SeletLastDataBaseUtilt(context);
		ReciveBodyInfoEntity lastBodyInfoEntity = getLastDatebBase.getLastBodyInfoEntity(muserName);
		
		long lastDate = lastBodyInfoEntity.getDate();
		
		//把毫秒值转化为年份、月份、星期数、日期数
		MSConversionToValues msConversionToValues = new MSConversionToValues();
		EntityConversionTime timeEntity = msConversionToValues.mSConverTOValues(mdate);
		if(lastDate!=0){
		//判断是不是同一天
		 boo = isSameDay(mdate,lastDate);
		}
		int weekNum  = timeEntity.getWeekNUM();
		int monthNum = timeEntity.getMonthNUM();
		int dayNum = timeEntity.getDayNUM();
		int yearNum = timeEntity.getYearNUM();
		float weight = bodyInfoEntity.getWeight();
		float bodyfat = bodyInfoEntity.getBodyFat();
		//如果是同一天就取平均值再更新数据
		if(boo){
			float lastweight = lastBodyInfoEntity.getWeight();
			float lastbodyFat = lastBodyInfoEntity.getBodyFat();
		
			float currentWeight = (lastweight+weight)/2;
			float currentFat = (lastbodyFat+bodyfat)/2;
			//lastDate为最后一次查询的时间
			mDataService.updateBodyInfo(lastDate, currentWeight, currentFat, weekNum, monthNum, dayNum, yearNum,muserName);

		}else{
			
			//不是同一天就直接插入数据
			mDataService.insertBodyInfo(mdate, weight, bodyfat, weekNum, monthNum, dayNum, yearNum,muserName);
		}
	}
	private	boolean isSameDay(long mdate,long lastDate) {
		String DATE_FORMAT = "yyyy-MM-dd";
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
		String mdateStr = sdf.format(mdate);
		String lastdateStr = sdf.format(lastDate);
		return mdateStr.equals(lastdateStr);
	}

}
